package com.file;


/**
 * Copyright (C) 2011 The Android Open Source Project 
 * Emial : guoyil199@163.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */ 
/**
 * Copyright (C) 2011 The Android Open Source Project 
 * Emial : guoyil199@163.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author THINK
 * @Email guoyil199@163.com
 * @version V1.0
 * @Date 2016年5月30日 下午3:30:12
 * @Title <B>todo</B>
 * <pre>java -Dfile.encoding=utf-8 -jar E:\work_space\QJXC_test</pre>
 */
public class ExtractResZhMain{
	private ConcurrentLinkedQueue<String> queue;
	public ExtractResZhMain(String rootPath){
		queue=new ConcurrentLinkedQueue<String>();
		queue.add("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
		queue.add("<resources>\n");
		new Thread(new ExtractResZh(rootPath,queue)).start();
		FileOutputStream out=createOutFile(rootPath);
		if(out!=null)
			new Thread(new WriteXmlFile(out, queue)).start();// 监听线程，不断从queue中读数据写入到文件中
	}
	
	
	private FileOutputStream createOutFile(String rootPath){
		FileOutputStream out=null;
		try {
			File file=new File(rootPath);
			if(file.isDirectory()){
				String f=file.getAbsolutePath()+"/res/values/string_ext.xml";
				file=new File(f);
				if(!file.exists()){
					file.createNewFile();
				}
				out= new FileOutputStream(file, true);
			}else{
				String f=file.getAbsolutePath();
				f=f.substring(0,f.lastIndexOf(File.separator));
				f=f+"/res/values/string_ext.xml";
				file=new File(f);
				if(!file.exists()){
					file.createNewFile();
				}
				out= new FileOutputStream(file, true);
			}
			return out;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		if(args==null || args.length<1){
			System.err.println("请输入项目地址....");
			return ;
		}
		System.out.println("在“com.util”包中创建Utils类，并添加 getString 方法. eg:<pre>"
				+"public class Utils {"
				+"    public static String getString(int resId){"
				+"			return $Conetext$.getString(resId);"
				+" 		}"
				+"}</pre>"
				);
		
		String path=args[0];
		System.out.println("path:"+path);
		new ExtractResZhMain(path);
		//testChe();
	}
	
	public static void testChe(){
		//匹配中文字符的正则表达式： [\u4e00-\u9fa5] 
//		匹配双字节字符(包括汉字在内)：[^\x00-\xff]
		String str = "RetroactionActivity.java,v 0.1 2015年9月9日 上午10:17:28 Exp";
		String regEx="[\\u4e00-\\u9fa5]";
		String regEx2="([\u4e00-\u9fa5]+)";
		String regEx3="([^\\x00-\\xff]+)";
		Pattern p = Pattern.compile(regEx3);    
		Matcher m = p.matcher( str );    
		String mv = null;    
		while (m.find()) {    
		   mv = m.group(0);    
		   System.out.println( mv );    
		}
	}
}

/**
 * @author Administrator
 * @Email guoyil199@163.com
 * @version V1.0
 * @Date 2015年9月16日 下午4:37:41
 * @Title <B>提取文件里的中文字符，xml ，Java 文件中</B>
 * <pre>
 * todo
 * </pre>
 */
 class ExtractResZh  implements Runnable{
	//private static final String path="C://Users//Administrator//Desktop//test//member//";
	
	public static final String FILE_XML=".xml";
	public static final String FILE_JAVA=".java";
	//private String isCurFileType=FILE_JAVA;
	
	private Pattern p;
	private Matcher m;
	public int count=0;
	private ArrayList<String>fileList;
	private String rootPath;
	private ConcurrentLinkedQueue<String> queue;
	
	
	public ExtractResZh(String rootPath,ConcurrentLinkedQueue<String> queue){
		fileList=new ArrayList<String>();
		this.rootPath=rootPath;
		this.queue=queue;
		String regEx = "[\\u4e00-\\u9fa5]";
		p = Pattern.compile(regEx);
		
	}
	

	@Override
	public void run() {
		readFileInDirectory(this.rootPath+"/src");
		readFileInDirectory(this.rootPath+"/res");
		init();
	}
	
	
	private void init(){
		System.out.println("-------------提取开始--------");
		if(fileList!=null && fileList.size()>0){
			//String sb="";
			for (String string : fileList) {
				readWriteFile(string);
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			queue.add("</resources>\n");
			System.out.println("-------------提取结束--------");
		}
	}
	
	
	public boolean isIncludeZh(String str) {
		m = p.matcher(str);
		return m.find();
	}
	
	
	private String isChinese(String strName,String prx,String fileType) {
	    char[] ch = strName.toCharArray();
	    HashMap<String, String>map=new HashMap<String, String>();
	    String str="";
	    for (int i = 0; i < ch.length; i++) {
	        char c = ch[i];
	        if (isChinese(c)) {
	        	str+=c;
	        	continue;
	        }
	        //System.out.print(str);
	        if(str!=null&&!"".equals(str)){
	        	if(c=='"'){
	        		map.put("str_"+prx+'_'+(count++),str);
	        		str="";
	        		continue;
	        	}
	        	str+=c;
	        	continue;
	        }
	        str="";
	    }
	   
	    if(map!=null &&map.size()>0){
	    	Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();  
	    	while (entries.hasNext()) {  
	    	    Map.Entry<String, String> entry = entries.next();  
	    	    //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
	    	    String key=entry.getKey();
	    	    String value=entry.getValue();
	    	    if(FILE_JAVA.equals(fileType)){
	    	    	strName= strName.replace("\""+value+"\"", "com.util.Utils.getString(R.string."+key+")");
	    	    }else if(FILE_XML.equals(fileType)){
	    	    	strName= strName.replace(""+value+"", "@string/"+key);
	    	    }
	    	    String content="<string name=\""+key+"\">"+value+"</string>\n";
	    	    System.out.print(content);
	    	    queue.add(content);
	    	    
	    	}  
	    }
	    return  strName;
	}
	 
	private  boolean isChinese(char c) {
	    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
	    if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
	            || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
	            || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
	            || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
	            || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
	            || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
	        return true;
	    }
	    return false;
	}
	

	
	public void readWriteFile(String filePath) {
		//InputStream stream=this.getClass().getResourceAsStream("/common.properties");  
        //InputStream stream=Thread.currentThread().getClass().getResourceAsStream("/common.properties");  
       // InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream("TestJava.txt");
        //InputStreamReader reader=new InputStreamReader(stream, "UTF-8");
		FileReader reader=null;
		BufferedReader br=null;
		FileWriter writer=null;
		BufferedWriter bw=null;
		try {
			// read file content from file
			File file=new File(filePath);
			if(!file.exists()){
				System.err.println(filePath+" ,文件不存在.");
				return;
			}
			String fileName=file.getName();
			String fileExt="";
			if(fileName.endsWith(FILE_JAVA)){
				fileExt=FILE_JAVA;
			}else if(fileName.endsWith(FILE_XML)){
				fileExt=FILE_XML;
			}
			String pre=fileName/*file.getName()*/.replaceAll("[.][^.]+$", "").toLowerCase();
			String inputTip="";
			inputTip="";
			inputTip+="<!-- start [";
			inputTip+=pre;
			inputTip+=" ]-->";
			System.out.println(inputTip);
			
			StringBuffer sb = new StringBuffer("");
            reader = new FileReader(file);
			br = new BufferedReader(reader);
			
			String str = null;
			while ((str = br.readLine()) != null) {
				if(!str.startsWith("//") &&
						!str.startsWith("/*") && 
						!str.startsWith("*") && 
						!str.startsWith("<!--")&&
						isIncludeZh(str)){
					sb.append(isChinese(str,pre,fileExt) + "\n");
				}else{
					sb.append(str + "\n");
				}
			}
			br.close();
			reader.close();
			//
			inputTip="";
			inputTip+="<!-- end [";
			inputTip+=pre;
			inputTip+=" ]-->";
			System.out.println(inputTip);
			//替换
			// write string to file
			writer = new FileWriter(filePath);
			bw = new BufferedWriter(writer);
			bw.write(sb.toString());
			bw.close();
			writer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(br!=null)try{br.close();}catch(Exception e){};
			if(reader!=null)try{reader.close();}catch(Exception e){};
			if(bw!=null)try{bw.close();}catch(Exception e){};
			if(writer!=null)try{writer.close();}catch(Exception e){};
		}
	}
	
	  /**
     * 遍历某目录下的所有文件
     * @param filePath
     * @param prefix .java / .xml
     * @return 文件名数组
     */
	public void readFileInDirectory(String filePath/*, String prefix*/) {
		File fileDir = new File(filePath);
		File[] files = fileDir.listFiles();
		for (File file : files) {
			if(file==null)continue;
			if(file.isDirectory()){
				readFileInDirectory(file.getAbsolutePath());
			}else{
				String fileName=file.getName();
				if (!("strings.xml".equals(fileName))&&
						!("string_ext.xml".equals(fileName)) 
						&& (fileName.endsWith(FILE_JAVA)||fileName.endsWith(FILE_XML))) {
					fileList.add(file.getAbsolutePath());
				}
			}
		}
	}
	
}
 
 class WriteXmlFile implements Runnable {
		private FileOutputStream out;
		private ConcurrentLinkedQueue<String> queue;
		private boolean isBreak=false;
		public WriteXmlFile() {
		}

		public WriteXmlFile(FileOutputStream out, ConcurrentLinkedQueue<String> queue) {
			this.out = out;
			this.queue = queue;
		}

		public void run() {
			while (!isBreak) {// 循环监听
				//System.out.println("Thread...");
				if (!queue.isEmpty()) {
					try {
						String content=queue.poll();
						if(content.startsWith("</resources>")){
							//System.out.println("end Thread");
							out.write(content.getBytes());
							isBreak=true;
						}else{
							out.write(content.getBytes());
							isBreak=false;
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

